<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace app\user\model;

use think\Db;
use think\Model;
use think\Session;

class UserModel extends Model {
	protected $type = [
		'more' => 'array',
	];

	public function doMobile($user) {

		
		$code = $user['code'];
		$appid = config("appid");
		$secret = config("secret");
		$url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
		$json = json_decode(file_get_contents($url), true);

		$openid = isset($json['openid'])?$json['openid']:false;
		$unionid = isset($json['unionid'])?$json['unionid']:false;


		$result = $this->where('mobile', $user['mobile'])->find();
		if($openid != $result['openid']){
			return ['status' => false, 'msg' => '请使用绑定微信的手机号登陆'];
		}
		if (!empty($result)) {
			$comparePasswordResult = cmf_compare_password($user['user_pass'], $result['user_pass']);
			$hookParam = [
				'user' => $user,
				'compare_password_result' => $comparePasswordResult,
			];
			hook_one("user_login_start", $hookParam);
			if ($comparePasswordResult) {
				// 拉黑判断。
				if ($result['user_status'] == 0) {
					return ['status' => false, 'msg' => '用户被禁用'];
				}
				session('user', $result->toArray());
				$data = [
					'last_login_time' => time(),
					'last_login_ip' => get_client_ip(0, true),
				];
				$this->where('id', $result["id"])->update($data);
				return ['status' => true, 'msg' => '登陆成功', 'data' => $result];
			}
			return ['status' => false, 'msg' => '登录失败'];
		}
		$hookParam = [
			'user' => $user,
			'compare_password_result' => false,
		];
		hook_one("user_login_start", $hookParam);
		return ['status' => false, 'msg' => '账号或密码错误'];
	}

	public function doWeixin($data) {
		$code = $data['code'];
		$appid = config("appid");
		$secret = config("secret");
		$url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
		$json = json_decode(file_get_contents($url), true);

		$openid = isset($json['openid'])?$json['openid']:false;
		$unionid = isset($json['unionid'])?$json['unionid']:false;
		$data = [
			'last_login_time' => time(),
			'last_login_ip' => get_client_ip(0, true),
		];
		if (!$openid) {
			return [
				'status' => false,
				'msg' => '微信授权失败',
				'data' => '',
			];
		} else {
			$result = $this->where('openid', $openid)->find();

			if (!empty($result)) {
				// 拉黑判断。
				if ($result['user_status'] == 0) {
					return [
						'status' => false,
						'msg' => '账号被禁用',
						'data' => '',
					];
				}
				$this->where('id', $result["id"])->update($data);
				$token = cmf_generate_user_token($result["id"], 'web');
				return [
					'status' => true,
					'msg' => '登陆成功',
					'data' => $result,
				];
			} else {
				return [
					'status' => false,
					'msg' => '账号没有注册',
					'data' => ['openid' => $openid,'unionid'=>$unionid],
				];
			}
		}
	}

	public function doName($user) {
		$result = $this->where('user_login', $user['user_login'])->find();
		if (!empty($result)) {
			$comparePasswordResult = cmf_compare_password($user['user_pass'], $result['user_pass']);
			$hookParam = [
				'user' => $user,
				'compare_password_result' => $comparePasswordResult,
			];
			hook_one("user_login_start", $hookParam);
			if ($comparePasswordResult) {
				// 拉黑判断。
				if ($result['user_status'] == 0) {
					return 3;
				}
				session('user', $result->toArray());
				$data = [
					'last_login_time' => time(),
					'last_login_ip' => get_client_ip(0, true),
				];
				$result->where('id', $result["id"])->update($data);
				$token = cmf_generate_user_token($result["id"], 'web');
				if (!empty($token)) {
					session('token', $token);
				}
				return 0;
			}
			return 1;
		}
		$hookParam = [
			'user' => $user,
			'compare_password_result' => false,
		];
		hook_one("user_login_start", $hookParam);
		return 2;
	}

	public function doEmail($user) {
		$result = $this->where('user_email', $user['user_email'])->find();

		if (!empty($result)) {
			$comparePasswordResult = cmf_compare_password($user['user_pass'], $result['user_pass']);
			$hookParam = [
				'user' => $user,
				'compare_password_result' => $comparePasswordResult,
			];
			hook_one("user_login_start", $hookParam);
			if ($comparePasswordResult) {

				// 拉黑判断。
				if ($result['user_status'] == 0) {
					return 3;
				}
				session('user', $result->toArray());
				$data = [
					'last_login_time' => time(),
					'last_login_ip' => get_client_ip(0, true),
				];
				$this->where('id', $result["id"])->update($data);
				$token = cmf_generate_user_token($result["id"], 'web');
				if (!empty($token)) {
					session('token', $token);
				}
				return 0;
			}
			return 1;
		}
		$hookParam = [
			'user' => $user,
			'compare_password_result' => false,
		];
		hook_one("user_login_start", $hookParam);
		return 2;
	}

	public function registerEmail($user) {
		$userQuery = Db::name("user");
		$result = $userQuery->where('user_email', $user['user_email'])->find();

		$userStatus = 1;

		if (cmf_is_open_registration()) {
			$userStatus = 2;
		}

		if (empty($result)) {
			$data = [
				'user_login' => '',
				'user_email' => $user['user_email'],
				'mobile' => '',
				'user_nickname' => '',
				'user_pass' => cmf_password($user['user_pass']),
				'last_login_ip' => get_client_ip(0, true),
				'create_time' => time(),
				'last_login_time' => time(),
				'user_status' => $userStatus,
				"user_type" => 2,
			];
			$userId = $userQuery->insertGetId($data);
			$data = $userQuery->where('id', $userId)->find();
			cmf_update_current_user($data);
			$token = cmf_generate_user_token($userId, 'web');
			if (!empty($token)) {
				session('token', $token);
			}
			return 0;
		}
		return 1;
	}

	public function registerMobile($user) {
		$result = Db::name("user")->where('mobile', $user['mobile'])->find();

		$userStatus = 1;

		if (cmf_is_open_registration()) {
			$userStatus = 2;
		}
		if (empty($result)) {
			$token = cmf_generate_user_token($user['mobile'], 'mobile');
			$regtime = date("Ymd", time());
			$count_today = $this->where(["FROM_UNIXTIME(create_time,'%Y%m%d')" => $regtime])->count();
			$count_today += 1;
			$count_today = str_pad($count_today, 4, '0', STR_PAD_LEFT);
			$data = [
				'user_login' => '',
				'user_email' => '',
				'mobile' => $user['mobile'],
				'user_nickname' => '',
				'user_pass' => cmf_password($user['user_pass']),
				'last_login_ip' => get_client_ip(0, true),
				'create_time' => time(),
				'last_login_time' => time(),
				'user_status' => $userStatus,
				"user_type" => 2, // 会员
				"token" => $token,
				'user_id' => $regtime . $count_today,
			];
			$userId = Db::name("user")->insertGetId($data);
			$data = Db::name("user")->where('id', $userId)->find();
			cmf_update_current_user($data);
			cmf_update_current_user($data);
			if (!empty($token)) {
				session('token', $token);
			}
			return json_encode([
				'status' => true,
				'msg' => '注册成功',
			]);
		} else {
			return json_encode([
				'status' => false,
				'msg' => '注册失败,用户已经注册',
			]);
		}
	}

	public function registerWx($user) {
		$openid = $user['openid'];
		if (empty($openid)) {
			return 3;
		}
		$result = Db::name("user")->where('openid', $openid)->find();

		$userStatus = 1;

		if (cmf_is_open_registration()) {
			$userStatus = 2;
		}

		if (empty($result)) {
			// $token = cmf_generate_user_token($user['wx_id'], 'weixin');
			// $data = [
			// 'user_login' => '',
			// 'user_email' => '',
			// 'wx_id' => $user['wx_id'],
			// 'user_nickname' => '',
			// // 'user_pass' => cmf_password($user['user_pass']),
			// 'last_login_ip' => get_client_ip(0, true),
			// 'create_time' => time(),
			// 'last_login_time' => time(),
			// 'user_status' => $userStatus,
			// "user_type" => 2 // 会员
			// // "token" => $token
			// ];
			$regtime = date("Ymd", time());
			$count_today = $this->where(["FROM_UNIXTIME(create_time,'%Y%m%d')" => $regtime])->count();
			$count_today += 1;
			$count_today = str_pad($count_today, 4, '0', STR_PAD_LEFT);
			$data['user_type'] = 2;
			$data['sex'] = $user['sex'];
			$data['last_login_time'] = time();
			$data['score'] = 0;
			$data['coin'] = 0;
			$data['balance'] = 0;
			$data['create_time'] = time();
			$data['user_status'] = $userStatus;
			$data['user_login'] = '';
			$data['user_pass'] = '';
			$data['user_nickname'] = $user['user_nickname'];
			$data['province'] = $user['province'];
			$data['city'] = $user['city'];
			$data['country'] = $user['country'];
			$data['user_email'] = '';
			$data['user_url'] = '';
			$data['avatar'] = $user['avatar'];
			$data['unionid'] = $user['unionid'];
			$data['signature'] = '';
			$data['last_login_ip'] = get_client_ip(0, true);
			$data['last_login_time'] = time();
			$data['user_activation_key'] = '';
			$data['mobile'] = '';
			$data['token'] = '';
			$data['openid'] = $openid;
			$data['reg_type'] = 1;
			$data['user_id'] = $regtime . $count_today;
			$userId = Db::name("user")->insertGetId($data);
			$data = Db::name("user")->where('id', $userId)->find();
			cmf_update_current_user($data);
			// cmf_update_current_user($data);
			// if (! empty($token)) {
			//     session('token', $token);
			// }
			return json_encode([
				'status' => true,
				'msg' => '注册成功',
			]);
		}
		return json_encode([
			'status' => false,
			'msg' => '注册失败,用户已经注册',
		]);
	}

	//更新用户的微信信息
	public function updatewxinfo($data) {
		// $WeixinController = new WeixinController();
		// $token = $WeixinController->getToken();

		// $openid = $data['openid'];
		// $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$token&openid=$openid&lang=zh_CN";
		// echo $url;die;
		// $userinfo = file_get_contents($url);
		// dump($userinfo);die;
		$userid = $data['userid'];
		unset($data['userid']);
		$result = $this->find($userid);
		if (!$result) {
			return json_encode([
				'status' => false,
				'msg' => '注册失败,用户未注册',
			]);
		}
		return $this->save($data, ['id' => $userid]);
	}

	/**
	 * 通过邮箱重置密码
	 *
	 * @param
	 *            $email
	 * @param
	 *            $password
	 * @return int
	 */
	public function emailPasswordReset($email, $password) {
		$result = $this->where('user_email', $email)->find();
		if (!empty($result)) {
			$data = [
				'user_pass' => cmf_password($password),
			];
			$this->where('user_email', $email)->update($data);
			return 0;
		}
		return 1;
	}

	/**
	 * 通过手机重置密码
	 *
	 * @param
	 *            $mobile
	 * @param
	 *            $password
	 * @return int
	 */
	public function mobilePasswordReset($mobile, $password) {
		$userQuery = Db::name("user");
		$result = $userQuery->where('mobile', $mobile)->find();
		if (!empty($result)) {
			$data = [
				'user_pass' => cmf_password($password),
			];
			$userQuery->where('mobile', $mobile)->update($data);
			return 0;
		}
		return 1;
	}

	public function editData($user) {
		$userId = cmf_get_current_user_id();

		if (isset($user['birthday'])) {
			$user['birthday'] = strtotime($user['birthday']);
		}

		if ($this->allowField('user_nickname,sex,birthday,user_url,signature,more')->save($user, [
			'id' => $userId,
		])) {
			$userInfo = $this->where('id', $userId)->find();
			cmf_update_current_user($userInfo->toArray());
			return 1;
		}
		return 0;
	}

	/**
	 * 用户密码修改
	 *
	 * @param
	 *            $user
	 * @return int
	 */
	public function editPassword($user) {
		// $userId = cmf_get_current_user_id();
		$userQuery = Db::name("user");
		// if ($user['password'] != $user['repassword']) {
		//     return 1;
		// }
		$pass = $userQuery->where('id', $user['userid'])->find();
		// if (! cmf_compare_password($user['old_password'], $pass['user_pass'])) {
		//     return 2;
		// }
		$data['user_pass'] = cmf_password($user['password']);
		$userQuery->where('id', $user['userid'])->update(['user_pass' => $data['user_pass']]);
		return 0;
	}

	public function comments() {
		$userId = cmf_get_current_user_id();
		$userQuery = Db::name("Comment");
		$where['user_id'] = $userId;
		$where['delete_time'] = 0;
		$favorites = $userQuery->where($where)
			->order('id desc')
			->paginate(10);
		$data['page'] = $favorites->render();
		$data['lists'] = $favorites->items();
		return $data;
	}

	public function deleteComment($id) {
		$userId = cmf_get_current_user_id();
		$userQuery = Db::name("Comment");
		$where['id'] = $id;
		$where['user_id'] = $userId;
		$data['delete_time'] = time();
		$userQuery->where($where)->update($data);
		return $data;
	}

	/**
	 * 绑定用户手机号
	 */
	public function bindingMobile($user) {
		// $userId = cmf_get_current_user_id();
		$userId = $user['userid'];
		$mobile = $user['mobile'];
		// Db::name("user")->where(['id'=>$userId])->update(['mobile'=>$mobile]);
		$token = cmf_generate_user_token($userId, 'wx');
		$this->where(['id' => $userId])->update(['mobile' => $mobile, 'token' => $token]);
		// $userInfo = Db::name("user")->where('id', $userId)->find();
		// cmf_update_current_user($userInfo);
		return 0;
	}

	/**
	 * 绑定用户邮箱
	 */
	public function bindingEmail($user) {
		$userId = cmf_get_current_user_id();
		$data['user_email'] = $user['username'];
		Db::name("user")->where('id', $userId)->update($data);
		$userInfo = Db::name("user")->where('id', $userId)->find();
		cmf_update_current_user($userInfo);
		return 0;
	}

	//绑定用户微信
	public function bindWeixin($code) {
		$appid = config("appid");
		$secret = config("secret");
		$url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
		$json = json_decode(cmf_curl_get($url), true);
		// $session_key = $json['session_key'];
		$openid = $json['openid'];
		return $openid;
	}
}
